{% extends "layout.html" %}
{% set active_page = "data" %}
{% set help_page = ["https://kizniche.github.io/Mycodo/Inputs/", dict_translation['input']['title']] %}

{% block title %} - {{dict_translation['input']['title']}}{% endblock %}

{% block head %}
<link rel="stylesheet" href="/static/css/gridstack.css" />
<link rel="stylesheet" href="/static/css/gridstack-custom.css" />
<script src="/static/js/gridstack-all.js"></script>

<link href="/static/css/toastr.min.css" rel="stylesheet"/>
<script src="/static/js/toastr.min.js"></script>

<script>
  $(document).ready(function () {
    toastr.options = {
      "closeButton": true,
      "debug": false,
      "newestOnTop": false,
      "progressBar": false,
      "positionClass": "toast-top-left",
      "preventDuplicates": false,
      "onclick": null,
      "showDuration": "300",
      "hideDuration": "1000",
      "timeOut": "15000",
      "extendedTimeOut": "10000",
      "showEasing": "swing",
      "hideEasing": "linear",
      "showMethod": "fadeIn",
      "hideMethod": "fadeOut"
    }
  });
</script>
{% endblock %}

{%- block body %}
  <!-- Route: /input -->
  <main role="main" class="container">
    {% include 'flash_messages.html' %}

    <h4>{{dict_translation['input']['title']}} <a href="{{help_page[0]}}" target="_blank"><span style="font-size: 16px" class="fas fa-question-circle"></span></a></h4>

    <div style="clear: both; padding: 0.5em 0;"></div>

    <form id="new_input_form" method="post" action="/input" style="padding-bottom: 0.5em">
      {{form_add_input.hidden_tag()}}
      <div class="row small-gutters" style="padding-left: 0.75em">
        <div class="col-auto">
          {{form_add_input.input_type(class_='selectpicker', **{'data-live-search': 'true', 'title': dict_translation['input']['title'] + ': ' + dict_translation['select_one']['title']})}}
        </div>
        <div class="col-auto">
          <input onclick="return $(this).processRequest(this, 'input_add');" name="input_add" value="{{_('Add')}}" class="btn btn-primary" type="button"/>
        </div>
      </div>
    </form>

    <div style="clear: both; padding: 1em 0;"></div>

    <div class="grid-stack">
    {% for each_input in table_input.query.all() -%}
      <div id="gridstack_input_{{each_input.unique_id}}"
        class="grid-stack-item"
        gs-id="{{each_input.unique_id}}"
        gs-x="0"
        gs-y="{{each_input.position_y}}"
        gs-w="24"
        gs-h="1"
        gs-no-resize="true">
        {% include 'pages/data_options/input_entry.html' %}
      </div> <!-- grid-stack-item -->
    {%- endfor -%}
    </div> <!-- grid-stack -->

    {% include 'admin/dependencies_install.html' %}

  </main>

  <div style="clear: both; padding-bottom: 1.5em;"></div>

  <script>
    let gridstack_item_height = $(".grid-stack-item-content").eq(0).outerHeight(true);

    // Grid
    let options = {
      cellHeight: gridstack_item_height + 5,
      column: 24,
      margin: 0,
      draggable: {
        handle: '.panel-heading'
      },
      float: false
    };
    let grid = GridStack.init(options);

    grid.on('change', function (event, items) {
      let gridstack_item_height = $(".grid-stack-item-content").eq(0).outerHeight(true);
      if (gridstack_item_height) {
        grid.cellHeight(gridstack_item_height + 5);
      }
      let serializedFull = grid.save(false);
      $.ajax({
        type: "POST",
        url: "/save_input_layout",
        headers: {"X-CSRFToken": "{{form_mod_input.csrf_token._value()}}"},
        data: JSON.stringify(serializedFull, null, '  '),
        contentType: "application/json; charset=utf-8",
        success: function (data) {}
      });
    });

    function popup_response(data) {
      if ('error' in data.data.messages && data.data.messages.error.length !== 0) {
        toastr['error']('Error: ' + data.data.messages.error.join(", "));
      }
      {% if not misc.hide_alert_warning %}
      if ('warning' in data.data.messages && data.data.messages.warning.length !== 0) {
        toastr['warning']('Warning: ' + data.data.messages.warning.join(", "));
      }
      {% endif %}
      {% if not misc.hide_alert_info %}
      if ('info' in data.data.messages && data.data.messages.info.length !== 0) {
        toastr['info']('Info: ' + data.data.messages.info.join(", "));
      }
      {% endif %}
      {% if not misc.hide_alert_success %}
      if ('success' in data.data.messages && data.data.messages.success.length !== 0) {
        toastr['success']('Success: ' + data.data.messages.success.join(", "));
      }
      {% endif %}
    }

    jQuery.fn.processRequest = function(button, action) {
      console.log("Action: ", action)
      if (action === 'input_add' ||
          action === 'input_duplicate' ||
          action === 'input_mod' ||
          action === 'input_delete' ||
          action === 'input_activate' ||
          action === 'input_deactivate' ||
          action === 'input_acquire_measurements' ||
          action === 'add_action' ||
          action === 'save_action' ||
          action === 'delete_action' ||
          action.startsWith('custom_button_')) {
        {% if not misc.hide_alert_info %}toastr['info']('Command sent. Please wait...');{% endif %}
        $.ajax({
          type: "POST",
          url: '/input_submit',
          headers: {"X-CSRFToken": "{{form_mod_input.csrf_token._value()}}"},
          data: $(button).parents('form').serialize() + '&' + action + '=1',
          success: function (data) {
            if ((action === 'input_add' || action === 'input_duplicate') && 'input_id' in data.data) {
              if ('dep_unmet' in data.data && data.data.dep_unmet.length > 0) {
                $(".dependencies_device_name").text(data.data.dep_name);
                $(".dependencies_device").text(data.data.dep_unmet);
                $(".dependencies_unmet").text(data.data.dep_list.join(", "));
                document.getElementById("dependency_unmet").value = data.data.dep_unmet;
                if (data.data.dep_message.length > 0) {
                  document.getElementById("dependencies_message").innerHTML = "<p>Message about dependencies: " + data.data.dep_message + "</p>";
                }
                $('#modal_config_dependency_install').modal('show');
                popup_response(data);
              } else {
                $.ajax({
                  type: "GET",
                  url: '/input?input_type=entry&input_id=' + data.data.input_id,
                  success: function (new_entry) {
                    if (data.data.messages.success.length !== 0) {
                      grid.addWidget('<div class="grid-stack-item" id="gridstack_input_' + data.data.input_id + '" gs-id="' + data.data.input_id + '">' + new_entry + '</div>', {
                        w: 24,
                        h: 1,
                        y: 999
                      });
                      {% if not hide_tooltips %}$('input[title]').tooltip({placement: 'top'});{% endif %}
                      if (action === 'input_duplicate') { $('#modal_config_' + data.data.duplicated_input_id).modal('hide'); }
                      $('#action_type_' + data.data.input_id).selectpicker('refresh');
                    }
                    popup_response(data);
                  },
                  error: function() {
                    toastr['error']('Error: Could not get new Input entry');
                  }
                });
              }
              return;
            }
            else if (action === 'add_action' && 'dep_unmet' in data.data && data.data.dep_unmet.length > 0) {
              $(".dependencies_device_name").text(data.data.dep_name);
              $(".dependencies_device").text(data.data.dep_unmet);
              $(".dependencies_unmet").text(data.data.dep_list.join(", "));
              document.getElementById("dependency_unmet").value = data.data.dep_unmet;
              if (data.data.dep_message.length > 0) {
                document.getElementById("dependencies_message").innerHTML = "<p>Message about dependencies: " + data.data.dep_message + "</p>";
              }
              $('#modal_config_dependency_install').modal('show');
            }

            if (data.data.messages.error.length === 0) {
              if (action === 'input_mod' && 'input_id' in data.data) {
                if ('return_text' in data.data.messages && data.data.messages.return_text.length > 0) {
                  document.getElementById("return_text_" + data.data.input_id).innerHTML = data.data.messages.return_text.join("<br/><br/>");
                }
                if ('name' in data.data.messages &&
                    document.getElementById("input_name_" + data.data.input_id)) {
                  if (document.getElementById("input_name_" + data.data.input_id).tagName === "DIV") {
                    document.getElementById("input_name_" + data.data.input_id).innerHTML = data.data.messages.name;
                  } else if (document.getElementById("input_name_" + data.data.input_id).tagName === "INPUT") {
                    document.getElementById("input_name_" + data.data.input_id).value = data.data.messages.name;
                  }
                }
              }
              else if (action === 'input_delete' && 'input_id' in data.data) {
                $('#modal_config_' + data.data.input_id).modal('hide');
                $('.modal-backdrop').remove();
                $(document.body).removeClass("modal-open");
                grid.removeWidget('#gridstack_input_' + data.data.input_id);
              }
              else if (action === 'input_activate' && 'input_id' in data.data) {
                $('#input_status_' + data.data.input_id).removeClass("inactive-background").addClass("active-background");
                document.getElementById('input_activate_' + data.data.input_id).style.display = "none";
                document.getElementById('input_deactivate_' + data.data.input_id).style.display = "";
              }
              else if (action === 'input_deactivate' && 'input_id' in data.data) {
                $('#input_status_' + data.data.input_id).removeClass("active-background").addClass("inactive-background");
                document.getElementById('input_activate_' + data.data.input_id).style.display = "";
                document.getElementById('input_deactivate_' + data.data.input_id).style.display = "none";
              }
              if (action === 'delete_action' && 'action_id' in data.data) {
                document.getElementById("mod_action_" + data.data.action_id).remove();
                popup_response(data);
              }
              if (action === 'add_action' && 'page_refresh' in data.data && data.data.page_refresh) {
                $.ajax({
                  type: "GET",
                  url: '/input?input_type=actions&input_id=' + data.data.input_id + '&action_id=' + data.data.action_id,
                  success: function (new_options) {
                    document.getElementById('mod_input_actions_' + data.data.input_id).insertAdjacentHTML('beforeend', (new_options));
                    popup_response(data);
                  },
                  error: function() {
                    toastr['error']('Error: Could not get Input Actions');
                  }
                });
              }
              else if (action === 'input_mod' && 'page_refresh' in data.data && data.data.page_refresh) {
                $.ajax({
                  type: "GET",
                  url: '/input?input_type=options&input_id=' + data.data.input_id,
                  success: function (new_options) {
                    $('#mod_input_' + data.data.input_id).html(new_options);
                    popup_response(data);
                  },
                  error: function() {
                    toastr['error']('Error: Could not get new Input options');
                  }
                });
              } else {
                popup_response(data);
              }
            } else {
              popup_response(data);
            }
          },
          error: function() {
            toastr['error']('Error: Could not communicate with server');
          }
        });
      }
    }
  </script>

{% endblock -%}
